package schema

import (
	"net/http"
	"github.com/go-xorm/xorm"
	// pq driver
	_ "github.com/lib/pq"
)

type QueryConf struct {
	Start  int    `schema:"start"`
	PgSize int    `schema:"pgsize"`
	Qseq   []int    `schema:"qseq"` //数组中的位置 id 还是name
	Qverb  []string `schema:"qverb"`  //什么样的where条件，大于小于还是前缀后缀
	Qpt    []string `schema:"qpt"`  // 筛选条件  名字中包含“胡”
	Odir   string `schema:"odir"`  //排序方式
	Oseq   int    `schema:"oseq"` //
}

func BasicQuery(eng *xorm.Engine, r *http.Request,
fields []string, rows interface{}, ob interface{}) int64 {
	qc := &QueryConf{}
	decoder := NewDecoder()
	r.ParseMultipartForm(200000000)
	err := decoder.Decode(qc, r.Form)
	if err!=nil{
		return 0
	}
	sess := eng.Cols(fields...)
	if qc.Oseq >-1 {
		if qc.Odir == "a" {
			sess = sess.Asc(fields[qc.Oseq])
		} else {
			sess = sess.Desc(fields[qc.Oseq])

		}
	}

	if qc.Qseq[0] < 0 {
		err := sess.Limit(qc.PgSize, qc.Start).Find(rows)
		if err!=nil{
			return 0
		}
		count, err := sess.Count(ob)
		return count

	}


	var ws, vs string
	for i:=0;i<len(qc.Qverb);i++{
		switch qc.Qverb[i][0] {
		case 'k': // like

			ws, vs = fields[qc.Qseq[i]]+" LIKE ? ", "%"+qc.Qpt[i]+"%"

		case 'p': // prefix
			ws, vs = fields[qc.Qseq[i]]+" LIKE ? ", qc.Qpt[i]+"%"
		case 's': // suffix
			ws, vs = fields[qc.Qseq[i]]+" LIKE ? ", "%"+qc.Qpt[i]
		case 'e': // equal
			ws, vs = fields[qc.Qseq[i]]+"=?", qc.Qpt[i]
		case 'g': // greater than
			ws, vs = fields[qc.Qseq[i]]+">?", qc.Qpt[i]
		case 'l': // less than
			ws, vs = fields[qc.Qseq[i]]+"<?", qc.Qpt[i]
		}
		if i==0{
			sess = sess.Where(ws, vs)

		}else{
			sess = sess.And(ws, vs)
		}

	}
	err = sess.Limit(qc.PgSize, qc.Start).Find(rows)


	if err != nil {
		return 0

	}

	count, err := sess.Count(ob)

	if err != nil {
		return 0

	}

	return count

}


